'''
* This is the projet for Brtc LlmOps Platform
* @Author Leon-liao <liaosiliang@alltman.com>
* @Description //TODO 
* @File: middleware.py
* @Time: 2025/11/18
* @All Rights Reserve By Brtc
'''
from dataclasses import dataclass
from typing import Optional

from flask import Request
from injector import inject

from internal.exception.exception import UnauthorizedException
from internal.model import Account
from internal.service import JwtService, AccountService


@inject
@dataclass
class Middleware:
    """应用中间件， 可以重写request_loader 与 unauthorized_handler"""
    jwt_service:JwtService
    account_service:AccountService

    def request_loader(self, request:Request)->Optional[Account]:
        """登录管理器"""
        #1、单独的为蓝图llmops-ai-platform 创建登录管理器
        print("Hello Wo  Yao Kai Shi Yan zheng")
        if request.blueprint == "llmops-ai-platform":
            #2、提取请求头的headers 中的信息
            auth_header = request.headers.get("Authorization")
            if not auth_header:
                raise UnauthorizedException("该接口需要授权才能访问， 请登陆后尝试！")

            #3、请求头信息中有没有空格分隔符，没有则验证失败， 格式， Authorization：Bearer access_token
            if " " not in auth_header:
                raise  UnauthorizedException("该接口需要授权才能访问， 授权格式验证失败！")

            #4、分割授权信息， 必须是 Bearer access_token
            auth_schema, access_token = auth_header.split(None, 1)
            if auth_schema.lower() != "bearer":
                raise UnauthorizedException("授权失败 ，请携带bearer 字段信息！！")
            #5、解析token信息得到用户的信息并返回
            payload = self.jwt_service.parse_token(access_token)
            account_id = payload["sub"]
            return self.account_service.get_account(account_id)
        else:
            return None